package com.util;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
import org.springframework.util.StringUtils;

/**
 * Date Utility Class This is used to convert Strings to Dates and Timestamps
 * 
 * <p>
 * <a href="DateUtil.java.html"><i>View Source</i></a>
 * </p>
 * 
 * @author raible
 * @version $Revision: 1 $ $Date: 2013-01-10 13:43:02 +0800 (星期四, 10 一月 2013) $
 */
public class DateUtil {
	public static int _EIGHT_HOUR = 8;
	public static String _DP_EUO = "MMM.d,yyyy";

	public static int _MIL_PER_MINUTE = 1000 * 60;
	/**
	 * 日期格式
	 */
	public static String datePattern = "yyyy-MM-dd";
	/**
	 * 时间格式
	 */
	public static String timePattern = "HH:mm:ss";

	public static String datetimePattern = "yyyy-MM-dd HH:mm:ss";

	/**
	 * Return default datePattern (MM/dd/yyyy)
	 * 
	 * @return a string representing the date pattern on the UI
	 */
	public static String getDatePattern() {
		return datePattern;
	}

	/**
	 * This method attempts to convert an Oracle-formatted date in the form
	 * dd-MMM-yyyy to mm/dd/yyyy.
	 * 
	 * @param aDate
	 *            date from database as a string
	 * @return formatted string for the ui
	 */
	public static final String getDate(Date aDate) {
		SimpleDateFormat df = null;
		String returnValue = "";

		if (aDate != null) {
			df = new SimpleDateFormat(datePattern);
			returnValue = df.format(aDate);
		}

		return (returnValue);
	}

	/**
	 * This method generates a string representation of a date/time in the
	 * format you specify on input
	 * 
	 * @param aMask
	 *            the date pattern the string is in
	 * @param strDate
	 *            a string representation of a date
	 * @return a converted Date object
	 * @see java.text.SimpleDateFormat
	 * @throws ParseException
	 *             转换异常
	 */
	public static final Date convertStringToDate(String aMask, String strDate)
			throws ParseException {
		SimpleDateFormat df = null;
		Date date = null;
		
		// 显示语言类型
		df = new SimpleDateFormat(aMask, Locale.ENGLISH);
		
		// 时区
		//df.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT")));

		try {
			date = df.parse(strDate);
		} catch (ParseException pe) {
			// log.error("ParseException: " + pe);
			throw new ParseException(pe.getMessage(), pe.getErrorOffset());
		}

		return (date);
	}

	/**
	 * This method generates a string representation of a date/time in the
	 * format you specify on input
	 * 
	 * @param strDate
	 *            a string representation of a date
	 * @return a converted Date object
	 * @see java.text.SimpleDateFormat
	 * @throws ParseException
	 *             转换异常
	 */
	public static final Date convertStringToDateTime(String strDate)
			throws ParseException {
		if (!StringUtils.hasLength(strDate)) {
			return null;
		}

		SimpleDateFormat df = null;
		Date date = null;
		df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		// 时区
		//df.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT")));

		if (strDate != null && strDate.trim().length() == 10) {
			strDate += " 00:00:00";
		}
		if (strDate != null && strDate.length() == 16) {
			strDate += ":00";
		}
		if (strDate != null && strDate.length() == 15) {
			strDate = strDate.substring(0, 5) + "0" + strDate.substring(5, 10)
					+ "0" + strDate.substring(10, 14) + ":00";
		}

		try {
			date = df.parse(strDate);
		} catch (ParseException pe) {
			// log.error("ParseException: " + pe);
			throw new ParseException(pe.getMessage(), pe.getErrorOffset());
		}

		return (date);
	}

	/**
	 * This method returns the given date time in the format: HH:MM:SS
	 * 
	 * @param theTime
	 *            the time string
	 * @return the given date/time
	 */
	public static String getTimeString(Date theTime) {
		return getDateTime(timePattern, theTime);
	}

	/**
	 * This method returns the current date in the format: MM/dd/yyyy
	 * 
	 * @return the current date
	 * @throws ParseException
	 *             转换异常
	 */
	public static Calendar getToday() throws ParseException {
		Date today = new Date();
		SimpleDateFormat df = new SimpleDateFormat(datePattern);

		// This seems like quite a hack (date -> string -> date),
		// but it works ;-)
		String todayAsString = df.format(today);
		Calendar cal = new GregorianCalendar();
		cal.setTime(convertStringToDate(todayAsString));

		return cal;
	}

	public static Date getNowDateTime() {
		Date today = new Date();
		SimpleDateFormat df = new SimpleDateFormat(datetimePattern);

		String todayAsString = df.format(today);
		try {
			return convertStringToDateTime(todayAsString);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String getNowDateTimeStr() {
		Date today = new Date();
		SimpleDateFormat df = new SimpleDateFormat(datetimePattern);
		
		return df.format(today);
	}

	public static Date getNowDate() {
		Date today = new Date();
		SimpleDateFormat df = new SimpleDateFormat(datePattern);

		String todayAsString = df.format(today);
		return convertStringToDate(todayAsString);
	}
	
	public static String getNowDateStr() {
		Date today = new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		
		return df.format(today);
	}
	
	public static String getNowDateStr2() {
		Date today = new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		
		return df.format(today);
	}
	
	

	/**
	 * This method generates a string representation of a date's date/time in
	 * the format you specify on input
	 * 
	 * @param aMask
	 *            the date pattern the string is in
	 * @param aDate
	 *            a date object
	 * @return a formatted string representation of the date
	 * 
	 * @see java.text.SimpleDateFormat
	 */
	public static final String getDateTime(String aMask, Date aDate) {
		SimpleDateFormat df = null;
		String result = "";

		if (aDate == null) {
			return result;
		}
		
		// 显示的语言,英文:Locale.ENGLISH，中文:Local.CHINESE
		df = new SimpleDateFormat(aMask, Locale.ENGLISH);
		// 时区
		//df.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT")));

		result = df.format(aDate);

		return (result);
	}

	/**
	 * This method generates a string representation of a date's date/time in
	 * the format you specify on input
	 * 
	 * @param aDate
	 *            a date object
	 * @return a formatted string representation of the date
	 * 
	 * @see java.text.SimpleDateFormat
	 */
	public static final String getDateTime(Date aDate) {
		SimpleDateFormat df = null;
		String returnValue = "";

		if (aDate == null) {
			// System.out.println("aDate is null!");
		} else {
			df = new SimpleDateFormat("yyyy-MM-ddHHmmss");
			returnValue = df.format(aDate);
		}

		return (returnValue);
	}

	/**
	 * This method generates a string representation of a date based on the
	 * System Property 'dateFormat' in the format you specify on input
	 * 
	 * @param aDate
	 *            A date to convert
	 * @return a string representation of the date
	 */
	public static final String convertDateToString(Date aDate) {
		return getDateTime(datePattern, aDate);
	}
	
	public static final String dateToStringNormal(Date aDate) {
		SimpleDateFormat df = null;
		String result = "";

		if (aDate == null) {
			return result;
		}

		df = new SimpleDateFormat(datePattern);

		result = df.format(aDate);

		return (result);
	}

	public static final String convertDateToString(String datePattern,
			Date aDate) {
		return getDateTime(datePattern, aDate);
	}

	/**
	 * This method converts a String to a date using the datePattern
	 * 
	 * @param strDate
	 *            the date to convert (in format MM/dd/yyyy)
	 * @return a date object
	 * 
	 * @throws ParseException
	 *             转换异常
	 */
	public static Date convertStringToDate(String strDate) {
		// throws ParseException {
		Date aDate = null;
		if (!StringUtils.hasLength(strDate)) {
			return null;
		}
		try {
			aDate = convertStringToDate(datePattern, strDate);
		} catch (ParseException pe) {
			try {
				aDate = convertStringToDate("yyyyMMdd", strDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			pe.printStackTrace();
		}

		return aDate;
	}

	public static Date strToDate(String strDate) {
		Date aDate = null;
		if (!StringUtils.hasLength(strDate)) {
			return null;
		}
		try {
			aDate = convertStringToDate(datePattern, strDate);
		} catch (ParseException pe) {
			pe.printStackTrace();
		}

		return aDate;
	}

	public static Date strToDateTime(String strDate) {
		Date aDate = null;
		if (!StringUtils.hasLength(strDate)) {
			return null;
		}
		try {
			aDate = convertStringToDate(datetimePattern, strDate);
		} catch (ParseException pe) {
			pe.printStackTrace();
		}

		return aDate;
	}

	/**
	 * 如果date1>date2 返回 1 = 0 < -1
	 * 
	 * @param date1
	 *            日期1
	 * @param date2
	 *            日期2
	 * @return 比较结果
	 */
	public static int compareDate(Date date1, Date date2) {
		String d1 = getDateTime(datePattern, date1);
		String d2 = getDateTime(datePattern, date2);

		if (d1 == null && d2 != null)
			return -1;
		else if (d1 != null && d2 == null)
			return 1;
		else if (d1 == null && d2 == null)
			return 0;
		else
			return d1.compareTo(d2);
	}

	public static String getQuarterByMonth(String month) {
		return "" + ((Integer.parseInt(month) - 1) / 3 + 1);

	}

	public static String getThisMonthFirstDay(String thisMonth) {
		String[] t = StringUtils.split(thisMonth, "-");

		return t[0] + "-" + t[1] + "-01";
	}

	/*
	 * public static String getLastMonthFirstDay(String thisMonth){ String[] t=
	 * StringUtils.split(thisMonth,"-");
	 * 
	 * if(Integer.parseInt(t[1])>1){ return t[0] + "-" +
	 * StringUtil.getFullChar((Integer.parseInt(t[1])-1)+"",'0',2)+"-01"; }else{
	 * return (Integer.parseInt(t[0])-1) + "-12-01"; } } public static String
	 * getNextMonthFirstDay(String thisMonth){ String[] t=
	 * StringUtils.split(thisMonth,"-");
	 * 
	 * if(Integer.parseInt(t[1])==12){ return (Integer.parseInt(t[0])+1) +
	 * "-01-01"; }else{ return t[0] + "-"+
	 * StringUtil.getFullChar((Integer.parseInt(t[1])+1)+"",'0',2)+"-01"; } }
	 */

	/**
	 * 联合统计日期和时段
	 * 
	 * @param dateStr
	 *            统计日期串
	 * @param timeStr
	 *            时段串
	 * @return 统计日期和时段联合串
	 */
	public static String unionDateAndTime(String dateStr, String timeStr) {
		Date date = null;
		// try {
		date = DateUtil.convertStringToDate(dateStr);
		/*
		 * } catch(ParseException e) { e.printStackTrace(); }
		 */
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.HOUR_OF_DAY, Integer.parseInt(timeStr));
		return DateUtil.getDateTime(cal.getTime());
	}

	/**
	 * 判断两个日期是否为同一年同一月
	 * 
	 * @param date1
	 *            日期一
	 * @param date2
	 *            日期二
	 * @return 同一年月true，不是同一年月false
	 */
	public static boolean isSameYearMonth(Date date1, Date date2) {
		boolean result = false;
		Calendar c1 = Calendar.getInstance();
		c1.setTime(date1);

		Calendar c2 = Calendar.getInstance();
		c2.setTime(date2);

		if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)
				&& c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH)) {
			result = true;
		}
		return result;
	}

	public static String getWeek(Date date) {
		SimpleDateFormat formatter = new SimpleDateFormat(" E ");
		String ctime = formatter.format(date);
		return ctime;
	}

	public static String getWeekOfYear(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setFirstDayOfWeek(Calendar.MONDAY);

		cal.setTime(date);

		String weekOfYear = String.valueOf(cal.get(Calendar.WEEK_OF_YEAR));
		if (weekOfYear.length() == 1) {
			weekOfYear = "0" + weekOfYear;
		}

		return String.valueOf(cal.get(Calendar.YEAR)) + weekOfYear;
	}

	public static String getWeekOfYear(String strDate) {
		Date date = DateUtil.convertStringToDate(strDate);
		return DateUtil.getWeekOfYear(date);
	}

	public static Timestamp string2Time(String dateString)
			throws java.lang.Exception {
		DateFormat dateFormat;
		// dateFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss",
		// Locale.ENGLISH);//设定格式
		dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
		dateFormat.setLenient(false);
		java.util.Date timeDate = dateFormat.parse(dateString);// util类型
		// java.sql.Date dateTime = new
		// java.sql.Date(timeDate.getTime());//sql类型
		return new Timestamp(timeDate.getTime());
	}

	public static Timestamp string2DateTime(String dateString)
			throws java.lang.Exception {
		if (!StringUtils.hasLength(dateString)) {
			return null;
		}
		DateFormat dateFormat;
		// dateFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss",
		// Locale.ENGLISH);//设定格式
		dateFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss", Locale.ENGLISH);
		dateFormat.setLenient(false);
		java.util.Date timeDate = dateFormat.parse(dateString);// util类型
		// java.sql.Date dateTime = new
		// java.sql.Date(timeDate.getTime());//sql类型
		return new Timestamp(timeDate.getTime());
	}

	public static Date string2Date(String dateString)
			throws java.lang.Exception {
		DateFormat dateFormat;
		// dateFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss",
		// Locale.ENGLISH);//设定格式
		dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
		dateFormat.setLenient(false);
		java.util.Date timeDate = dateFormat.parse(dateString);// util类型
		return timeDate;
	}

	public static String date2String(Date date, DateFormat dateFormat) {
		return dateFormat.format(date);
	}

	public static Date addDay(Date date, int dayNum) {
		GregorianCalendar gc = new GregorianCalendar();
		gc.setTime(date);
		gc.add(GregorianCalendar.DATE, dayNum);
		return gc.getTime();
	}

	public static String addDay(String inDate, int dayNum) {
		return dateToString(addDay(strToDate(inDate), dayNum));
	}

	public static Date addHour(Date date, int hoursToAdd) {
		GregorianCalendar gc = new GregorianCalendar();
		gc.setTime(date);
		gc.add(GregorianCalendar.HOUR, hoursToAdd);
		return gc.getTime();
	}

	public static Date toGMT(Date date) {
		return addHour(date, _EIGHT_HOUR);
	}

	public static Date addSecond(Date date, int num) {
		GregorianCalendar gc = new GregorianCalendar();
		gc.setTime(date);
		gc.add(GregorianCalendar.SECOND, num);
		return gc.getTime();

	}

	public static Date getBeginTimeOfToday(int days) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(new Date());
		calendar.add(Calendar.DATE, days);
		calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DATE), 0, 0, 0);
		return calendar.getTime();
	}

	public static Date getEndTimeOfToday(int days) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(new Date());
		calendar.add(Calendar.DATE, days);
		calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DATE), 23, 59, 59);
		return calendar.getTime();
	}

	/**
	 * 判断日期是否在某个特定时间区之内
	 * 
	 * @param start
	 * @param end
	 * @param now
	 */
	public static boolean ifBetweenDateArea(Date start, Date end, Date now) {
		if (now == null) {
			return false;
		}
		if (start != null && end != null) {
			if ((now.compareTo(start) == 0 || now.after(start))
					&& (now.compareTo(end) == 0 || now.before(end))) {
				return true;
			}
		} else if (start != null && end == null) {
			if (now.compareTo(start) == 0 || now.after(start)) {
				return true;
			}
		} else if (start == null && end != null) {
			if (now.compareTo(end) == 0 || now.before(end)) {
				return true;
			}
		} else if (start == null && end == null) {
			return true;
		}
		return false;
	}

	@SuppressWarnings("static-access")
	public static Date getTransDate(Date date, boolean isFullDate) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		if (0 == calendar.get(calendar.HOUR)
				&& 0 == calendar.get(calendar.MINUTE)
				&& 0 == calendar.get(calendar.SECOND)) {

			if (isFullDate) {
				calendar.set(calendar.get(calendar.YEAR),
						calendar.get(calendar.MONTH),
						calendar.get(calendar.DATE), 23, 59, 59);
			} else {
				calendar.set(calendar.get(calendar.YEAR),
						calendar.get(calendar.MONTH),
						calendar.get(calendar.DATE), 0, 0, 0);
			}
		}
		return calendar.getTime();
	}

	public String convertTimestamp(Timestamp dateTime, TimeZone timezone,
			String pattern, Locale locale) {
		if (pattern == null) {
			pattern = "yyyy-MM-dd HH:mm";
		}

		if (locale == null) {
			locale = Locale.US;
		}

		DateFormat format = null;
		if (pattern != null) {
			format = new SimpleDateFormat(pattern, locale);
		}

		format.setTimeZone(timezone);

		return format.format(dateTime);
	}

	/**
	 * 按时区转化时间
	 * 
	 * @param dateTime
	 *            待转化的日期时间
	 * @param timezone
	 *            时区
	 * @return 按2005-08-25 15:09格式转化好的字串
	 */
	public String convertTimestamp(Timestamp dateTime, TimeZone timezone) {

		return this.convertTimestamp(dateTime, timezone, null, null);
	}

	/**
	 * 按时区转化时间
	 * 
	 * @param dateTime
	 *            待转化的日期时间
	 * @param timezone
	 *            时区
	 * @return 按2005-08-25 15:09:00格式转化好的字串
	 */
	public String convertTimestamp(Timestamp dateTime, TimeZone timezone,
			String pattern) {
		return this.convertTimestamp(dateTime, timezone, pattern, null);
	}

	public static String convertTimestampToDate(Timestamp dateTime) {
		String pattern = "yyyy-MM-dd";
		Locale locale = Locale.US;

		DateFormat format = null;
		if (pattern != null) {
			format = new SimpleDateFormat(pattern, locale);
		}

		return format.format(dateTime);

	}

	public static String Timestamp2StringPattenYYYYMMDD(Timestamp time)
			throws Exception {
		if (time == null) {
			return "";
		}

		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
		sdf1.setTimeZone(TimeZone.getDefault());

		return sdf1.format(time);
	}

	public static final String dateToString(Date aDate) {
		SimpleDateFormat df = null;
		String returnValue = "";

		if (aDate == null) {
			// System.out.println("aDate is null!");
		} else {
			df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			// 时区
			//df.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT")));

			returnValue = df.format(aDate);
		}

		return (returnValue);
	}

	public static final Long dateToLong(Date aDate, String aMask) {
		SimpleDateFormat df = null;
		Long result = null;

		if (aDate == null) {
			return result;
		}

		df = new SimpleDateFormat(aMask);
		result = new Long(df.format(aDate));

		return (result);
	}

	public static String Timestamp2StringPattenYYYYMMDDHHMMss(Timestamp time)
			throws Exception {
		if (time == null) {
			return "";
		}
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHMMss");
		sdf1.setTimeZone(TimeZone.getDefault());
		return sdf1.format(time);
	}

	/**
	 * 验证日期有效性方法1, 需要验证yyyy-MM-dd的时间数据， MM必须为0X，如02,03,04
	 * 
	 * @param sDate
	 *            author cc.hou date: 2011-1-17
	 */
	public static boolean isValidDate(String sDate) {
		String datePattern1 = "\\d{4}-\\d{2}-\\d{2}";
		String datePattern2 = "^((\\d{2}(([02468][048])|([13579][26]))"
				+ "[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|"
				+ "(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?"
				+ "((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?("
				+ "(((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?"
				+ "((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";
		if ((sDate != null)) {
			Pattern pattern = Pattern.compile(datePattern1);
			Matcher match = pattern.matcher(sDate);
			if (match.matches()) {
				pattern = Pattern.compile(datePattern2);
				match = pattern.matcher(sDate);
				return match.matches();
			} else {
				return false;
			}
		}
		return false;
	}

	/**
	 * 验证时间有效性方法2, 需要验证yyyy-MM-dd的时间数据 MM可以为0X,也可以为X,如02或2
	 * 
	 * @param dateString
	 *            author cc.hou date: 2011-1-17
	 */
	public static boolean validate(String dateString) {
		// 使用正则表达式 测试 字符 符合 dddd-dd-dd 的格式(d表示数字)
		Pattern p = Pattern.compile("\\d{4}+[-]\\d{1,2}+[-]\\d{1,2}+");
		Matcher m = p.matcher(dateString);
		if (!m.matches()) {
			return false;
		}

		// 得到年月日
		String[] array = dateString.split("-");
		int year = Integer.valueOf(array[0]);
		int month = Integer.valueOf(array[1]);
		int day = Integer.valueOf(array[2]);

		if (month < 1 || month > 12) {
			return false;
		}
		int[] monthLengths = new int[] { 0, 31, -1, 31, 30, 31, 30, 31, 31, 30,
				31, 30, 31 };
		if (isLeapYear(year)) {
			monthLengths[2] = 29;
		} else {
			monthLengths[2] = 28;
		}
		int monthLength = monthLengths[month];
		if (day < 1 || day > monthLength) {
			return false;
		}
		return true;
	}

	/** 是否是闰年 */
	private static boolean isLeapYear(int year) {
		return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
	}

	/**
	 * 查询用的 <= 某天时间。
	 * 
	 * @param aDate
	 * @return String
	 */
	public static String dateToString2(Date aDate) {
		SimpleDateFormat df = null;
		String returnValue = "";

		if (aDate == null) {
			// System.out.println("aDate is null!");
		} else {
			df = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
			returnValue = df.format(aDate);
		}

		return (returnValue);
	}

	public static Date convertDateByTimeZone(Date serverDate, TimeZone timezone) {
		if (timezone == null) {
			return serverDate;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		sdf.setTimeZone(timezone);

		String serverDateStr = sdf.format(serverDate);
		Date finalServerDate = null;

		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			finalServerDate = sdf1.parse(serverDateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return finalServerDate;
	}

	@SuppressWarnings("deprecation")
	public static String getWeekendName(Date date) {
		if (6 == date.getDay()) {
			return "Saturday";
		}

		if (0 == date.getDay()) {
			return "Sunday";
		}

		return "";
	}

	public static int diffTime(Date from, Date to) {
		long diff = to.getTime() - from.getTime();

		return (int) (diff / _MIL_PER_MINUTE);
	}

	/**
	 * 根据出生日期计算年龄
	 * 
	 * @param from
	 * @param to
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static int getAge(Date birthDate) {
		if (birthDate == null) {
			return 0;
		}

		if (compareDate(getNowDate(), birthDate) < 0) {
			return 0;
		}

		return getNowDate().getYear() - birthDate.getYear();
	}

	/**
	 * 取得指定日期所在周的第一天
	 */
	public static Date getFirstDayOfWeek(Date date) {
		Calendar c = new GregorianCalendar();
		c.setFirstDayOfWeek(Calendar.MONDAY);
		c.setTime(date);
		c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
		return c.getTime();
	}

	/**
	 * 取得指定日期所在周的最后一天
	 */
	public static Date getLastDayOfWeek(Date date) {
		Calendar c = new GregorianCalendar();
		c.setFirstDayOfWeek(Calendar.MONDAY);
		c.setTime(date);
		c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
		return c.getTime();
	}

	/**
	 * 取得指定日期所在周的某一天
	 */
	public static int getDayOfWeek(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.DAY_OF_WEEK);
	}

	public static int getDayOfWeek(String strDate) {
		Date date = DateUtil.convertStringToDate(strDate);

		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.DAY_OF_WEEK);
	}

	public static String getCurrentYearMonth() {
		Date date = new Date();
		return convertDateToString("yyyy-MM", date);
	}
	
	public static String getCurrentYearMonthStr() {
		Date date = new Date();
		return convertDateToString("yyyyMM", date);
	}

	public static String toWeekDayName(int dayOfWeek) {
		if (dayOfWeek == 1) {
			return "sunday";
		}
		if (dayOfWeek == 2) {
			return "monday";
		}
		if (dayOfWeek == 3) {
			return "tuesday";
		}
		if (dayOfWeek == 4) {
			return "wednesday";
		}
		if (dayOfWeek == 5) {
			return "thursday";
		}
		if (dayOfWeek == 6) {
			return "friday";
		}
		if (dayOfWeek == 7) {
			return "saturday";
		}
		return "";
	}

	public static String toWeekDayDesc(String weekDayName) {
		if (weekDayName.equals("sunday")) {
			return "周日";
		}
		if (weekDayName.equals("monday")) {
			return "周一";
		}
		if (weekDayName.equals("tuesday")) {
			return "周二";
		}
		if (weekDayName.equals("wednesday")) {
			return "周三";
		}
		if (weekDayName.equals("thursday")) {
			return "周四";
		}
		if (weekDayName.equals("friday")) {
			return "周五";
		}
		if (weekDayName.equals("saturday")) {
			return "周六";
		}
		return "";
	}

	public static Date strYearToDate(String strDate) {
		Date aDate = null;
		if (!StringUtils.hasLength(strDate)) {
			return null;
		}
		try {
			aDate = convertStringToDate("yyyy", strDate);
		} catch (ParseException pe) {
			pe.printStackTrace();
			return null;
		}

		return aDate;
	}

	public static int getDateYear(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);

		return cal.get(Calendar.YEAR);
	}
	
	public static Date getDateByWeek(int year, int week) {
		Calendar cal = Calendar.getInstance();
		cal.setFirstDayOfWeek(Calendar.MONDAY);
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.DAY_OF_YEAR, 7 * (week - 1)  );
		return cal.getTime();
	}
	
	public static Date getStartDateOfWeek(String week){
		Integer year = Integer.parseInt( org.apache.commons.lang3.StringUtils.left(week, 4) );
		Integer iWeek = Integer.parseInt(  org.apache.commons.lang3.StringUtils.removeStart( 
				org.apache.commons.lang3.StringUtils.right(week, 2), 
				"0"));
		Date date = DateUtil.getDateByWeek(year, iWeek);
		return DateUtil.getFirstDayOfWeek( date ) ;
	}
	

	//public static void main(String[] args) throws Exception {
		//System.out.println( DateUtil.convertDateToString(DateUtil._DP_EUO, null) );
		// System.out.println( "2014-01-02".compareTo("2014-01-01") );

		// Date date = new Date();
		// System.out.println( getWeekOfYear(date) );

		/*
		 * Date date2 = DateUtil.string2Date("2014-03-24"); System.out.println(
		 * DateUtil.getWeekOfYear( date2 ) ); System.out.println(
		 * DateUtil.getDayOfWeek(date2) );
		 * 
		 * Date date = DateUtil.string2Date("2014-03-25"); System.out.println(
		 * DateUtil.getWeekOfYear( date ) ); System.out.println(
		 * DateUtil.getDayOfWeek(date) );
		 * 
		 * Date date1 = DateUtil.string2Date("2014-03-26"); System.out.println(
		 * DateUtil.getWeekOfYear( date1 ) ); System.out.println(
		 * DateUtil.getDayOfWeek(date1) );
		 * 
		 * if ( date.before(date1) ){ System.out.println( "date before date1" );
		 * }
		 */
		//System.out.println(getFirstDayOfNextHalfMonth());
		//System.out.println(getDateOfAddOrSubMonth(new Date(), -3));
		
	//}
	
	/**
	 * 获得当月第一天的Date
	 * @return
	 * @throws ParseException
	 */
	public static Date getFirstDayOfCurrentMonth() throws ParseException{
		Calendar cal = Calendar.getInstance();   
		SimpleDateFormat dtf=new SimpleDateFormat("yyyy-MM-dd");  
		//当前月的第一天            
        cal.set(GregorianCalendar.DAY_OF_MONTH, 1);   
        Date beginTime =  cal.getTime();  
        return dtf.parse(dtf.format(beginTime));
	}
	
	/**
	 * 获得下个月第一天的Date
	 * @return
	 * @throws ParseException
	 */
	public static Date getFirstDayOfNextMonth() throws ParseException{
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat dtf=new SimpleDateFormat("yyyy-MM-dd");  
		// 当前月的第一天            
        cal.set(GregorianCalendar.DAY_OF_MONTH, 1);
        int month = cal.get(Calendar.MONTH);
        cal.set(GregorianCalendar.MONTH, ++month);
        Date beginTime =  cal.getTime();  
        return dtf.parse(dtf.format(beginTime));
	}
	
	/**
	 * 获取下半个月的第一天
	 * @author larry
	 * @date 2017年6月16日
	 * @return
	 * @throws ParseException
	 */
	public static Date getFirstDayOfNextHalfMonth() throws ParseException{
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat dtf=new SimpleDateFormat("yyyy-MM-dd");  
		int day  = cal.get(Calendar.DAY_OF_MONTH);
		if (day<=15) {
			cal.set(GregorianCalendar.DAY_OF_MONTH, 16);
		}else {
			cal.set(GregorianCalendar.DAY_OF_MONTH, 1);
	        int month = cal.get(Calendar.MONTH);
	        cal.set(GregorianCalendar.MONTH, ++month);
		}
       
        Date beginTime =  cal.getTime();  
        return dtf.parse(dtf.format(beginTime));
	}
	
	/**
	 * 指定日期加减天数
	 * @author larry
	 * @date 2017年6月16日
	 * @param date
	 * @return
	 */
	public static Date getDateOfAddOrSubDay(Date date,int day) {
		Calendar calendar = Calendar.getInstance();
	    calendar.setTime(date); 
	    calendar.add(GregorianCalendar.DAY_OF_MONTH,day);//把日期往后增加n天.整数往后推,负数往前移动 
	    return calendar.getTime();
	}
	
	/**
	 * 指定日期加减月
	 * @author larry
	 * @date 2017年6月23日
	 * @param date
	 * @param day
	 * @return
	 */
	public static Date getDateOfAddOrSubMonth(Date date,int month) {
		Calendar calendar = Calendar.getInstance();
	    calendar.setTime(date); 
	    calendar.add(GregorianCalendar.MONTH,month);//把日期往后增加n月.整数往后推,负数往前移动 
	    return calendar.getTime();
	}
	
	/**
	 * 比较是否是同一天
	 * @author larry
	 * @date 2017年9月1日
	 * @param dt1
	 * @param dt2
	 * @return
	 */
	public static boolean sameDate(Date dt1 , Date dt2 ) {  
        LocalDate ld1 = new LocalDate(dt1,DateTimeZone.forOffsetHours(8));  
        LocalDate ld2 = new LocalDate(dt2,DateTimeZone.forOffsetHours(8));
        return ld1.equals( ld2 );  
    }  
	
	/**
	 * 聊天列表消息时间
	 * @author larry
	 * @date 2017年8月18日
	 * @param date
	 * @return
	 */
	public static String parseDateToStringForChat(Date date) {
		if (date == null) {
			return "";
		}
		Date now = new Date();
		
		if (sameDate(date,now)) {
			String str = convertDateToString("ah:mm", date);
			str = str.replace("AM", "上午");
			str = str.replace("PM", "下午");
			return str;
		}else {
			return convertDateToString("yyyy/M/d", date);
		}
	}
	
	/**
	 * 聊天信息显示的时间
	 * @author larry
	 * @date 2017年9月1日
	 * @param date
	 * @return
	 */
	public static String parseDateToStringForChatMsg(Date date) {
		if (date == null) {
			return "";
		}
		Date now = new Date();
		
		if (sameDate(date,now)) {
			String str = convertDateToString("ah:mm", date);
			str = str.replace("AM", "上午");
			str = str.replace("PM", "下午");
			return str;
		}else {
			String str = convertDateToString("yyyy年M月d日  ah:mm", date);
			str = str.replace("AM", "上午");
			str = str.replace("PM", "下午");
			return str;
		}
	}
	
	public static void main(String[] args) throws Exception {
		//System.out.println(parseDateToStringForChatMsg(new Date()));
	}

}